<?php

namespace App\Clients\Lakala;

use App\Clients\JinShouFu\JinShouFuClient;
use App\Clients\Yisheng\YishengClient;
use App\Services\JinShouFuHelper;
use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\Exception\GuzzleException;
use Psr\Http\Message\ResponseInterface;

abstract class LakalaClient extends YishengClient
{

    protected $cookieJar;

    public function handleQeqData($postData){
        $requestTime = date("YmdHis");
        $requestId = $requestTime.rand(1000000,9999999);
        $postData["requestId"] = $requestId;
        $postData["requestTime"] = $requestTime;
        $postData["reqTime"] = $requestTime;
        $postData["systemCode"] = "MERDASH";
        $postData["version"] = "1.0";
        return $postData;
    }

    public function setCookieJar($cookieJar){
        $this->cookieJar = $cookieJar;
    }

    /**
     * @throws GuzzleException
     * @throws Exception
     */
    public function sliderOffset(){
        $client = new Client(["verify"=>false]);
        $requestTime = date("YmdHis");
        $requestId = $requestTime.rand(1000000,9999999);
        $url = "https://m2.lakala.com/m/lamsmerdash/slider/get";
        $postData = [
            "requestId"=>$requestId,
            "requestTime"=>$requestTime,
            "systemCode"=>"MERDASH",
            "version"=>"1.0",
        ];
        $response = $client->post($url,["json"=>$postData])->getBody()->getContents();
        $response = json_decode($response,true);
        $imageBase64 = $response["data"]["original"];
//        file_put_contents("a.jpg",base64_decode($imageBase64));
//        exit();
        $token = $response["data"]["token"];
        $offsetY = $response["data"]["y"];
        $url = "http://www.fdyscloud.com.cn/tuling/predict";
        $postData = [
            "username"=>"zhyichao1200",
            "password"=>"qw63878363",
            "b64"=>$imageBase64,
            "ID"=>"05119180",
            "version"=>"3.1.1",
        ];
        $response = $client->post($url,["json"=>$postData])->getBody()->getContents();
        $response = json_decode($response,true);
        if(empty($response["data"])) throw new Exception("未识别到图片");
        $offset = $response["data"]["滑块"]["Y坐标值"] - $offsetY;
        $offsetX = ($response["data"]["滑块"]["X坐标值"] - $offset).".".rand(1000000,9999999);
        return [
            "token"=>$token,
            "x"=>$offsetX,
            "y"=>$offsetY
        ];
    }

    public function login(): void{
        $sliderData = [];
        for($i=0;$i<=5;$i++){
            try{
                $sliderData = $this->sliderOffset();
                break;
            }catch (Exception $e){
                if($i == 5) throw $e;
                sleep(1);
            }
        }
        $requestTime = date("YmdHis");
        $requestId = $requestTime.rand(1000000,9999999);
        $postData = [
            "account"=>$this->account->name,
            "pwd"=>$this->account->password,
            "requestId"=>$requestId,
            "requestTime"=>$requestTime,
            "sliderReq"=>$sliderData,
            "systemCode"=>"MERDASH",
            "version"=>"1.0",
        ];
        $url = "https://m2.lakala.com/m/lamsmerdash/account/pwdLogin";
        $client = new Client(["verify"=>false]);
        $headers = [
            "User-Agent"=>'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.6045.9 Safari/537.36',
        ];
        $response = $client->post($url,["json"=>$postData,"headers"=>$headers])->getBody()->getContents();
        $response = json_decode($response,true);
        $response = $response["data"];
        $headers["AUTHORIZATION"] = $response["authorization"];
//        $cookieJar = new CookieJar();
//        $client = new Client([
//            "verify"=>false,
//            "http_errors"=>false,
//            'cookies' => $cookieJar,
//        ]);
//        $postData = $this->handleQeqData(["isGuest"=>true]);
//        $url = "https://m2.lakala.com/m/a/lams/staff/queryMerListByCustIdAndStatusRoleV2";
//        $content = $client->post($url,["json"=>$postData,"headers"=>$headers])->getBody()->getContents();
//        $cookies = $cookieJar->toArray();
//        $cookieStr = [];
//        foreach ($cookies as $cookie){
//            $cookieStr[] = $cookie["Name"]."=".$cookie["Value"];
//        }
//        $cookieStr = implode("; ",$cookieStr);
//        $response["cookies"] = $cookieStr;
        $this->account->cookies = json_encode($response);
        $this->account->login_status = 1;
        $this->account->logout_at = date("Y-m-d H:i:s",time() + 86400 * 10);
        $this->account->save();
    }

    public function headers($other = []): array
    {
        $cookies = empty($this->cookieJar) ? json_decode($this->account->cookies,true) : $this->cookieJar;
        $headers = [
            "User-Agent"=>'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.6045.9 Safari/537.36',
            "AUTHORIZATION"=>$cookies["authorization"],
            //"Cookie"=>$cookies["cookies"],
        ];
        !empty($cookies["cookies"]) and $headers["Cookie"] = $cookies["cookies"];
//        var_dump($headers);
//        exit();
        return array_merge($headers,$other);
    }

    protected function isLogout(ResponseInterface $response){
        $content = $response->getBody()->getContents();
        //var_dump($content);
        $content = json_decode($content,true);
        if($content["code"] == "GW0001" || $content["code"] == "MP3199999" || $content["code"] == "E100004"){
            $this->account->login_status = 0;
            $this->account->save();
            throw new Exception("掉线了");
        }
        return $content;
    }
}
